﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Vra.DataAccess;
using System.Data;
using System.Data.SqlClient;

namespace ViewRidgeAssistant
{
    /// <summary>
    /// Логика взаимодействия для SettingsWindow.xaml
    /// </summary>
    public partial class SettingsWindow : Window
    {
        private SettingsDao _settings = new SettingsDao();
        private bool recstatus; // f*cking windows security

        private void LoadSettings()
        {
            if (_settings.GetSettings() != null)
            {
                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
                builder.ConnectionString = _settings.GetSettings();

                this.tbServer.Text = builder.DataSource;
                this.tbDataBase.Text = builder.InitialCatalog;

                if (builder.IntegratedSecurity & !recstatus)
                {
                    this.cbAuth.IsChecked = true;
                }
                else
                {
                    this.tbPassword.Text = builder.Password;
                    this.tbUser.Text = builder.UserID;
                }
            }
            else
            {
                this.tbServer.Text = "127.0.0.1";
                this.tbDataBase.Text = "vra_db";
                this.cbAuth.IsChecked = true;
            }
        }

        public SettingsWindow()
        {
            InitializeComponent();
            LoadSettings();
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void cbAuth_Checked(object sender, RoutedEventArgs e)
        {
            this.tbUser.Text = "";
            this.tbPassword.Text = "";
            this.tbUser.IsEnabled = false;
            this.tbPassword.IsEnabled = false;
        }

        private void cbAuth_Uncheked(object sender, RoutedEventArgs e)
        {
            this.tbUser.IsEnabled = true;
            this.tbPassword.IsEnabled = true;
            this.recstatus = true; // велосипед. Потом надо исправить.
            LoadSettings();
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult result = MessageBox.Show("Сохранить изменения?", "Изменение настроек подключения", MessageBoxButton.YesNo, MessageBoxImage.Warning);

            if (result != MessageBoxResult.Yes) return;

            this._settings.SetSettings(this.tbServer.Text, this.tbDataBase.Text, this.tbUser.Text, this.tbPassword.Text);
           
            this.Close();
        }
    }
}
